package cn.caskm.souvenirshopsystem.service.impl;

import cn.caskm.souvenirshopsystem.constants.BizConstants;
import cn.caskm.souvenirshopsystem.domain.Result;
import cn.caskm.souvenirshopsystem.domain.dto.PageDTO;
import cn.caskm.souvenirshopsystem.domain.po.*;
import cn.caskm.souvenirshopsystem.domain.query.MyOrderQuery;
import cn.caskm.souvenirshopsystem.domain.query.PageQuery;
import cn.caskm.souvenirshopsystem.domain.vo.MyOrderVO;
import cn.caskm.souvenirshopsystem.exceptions.BizException;
import cn.caskm.souvenirshopsystem.mapper.GoodsOrderMapper;
import cn.caskm.souvenirshopsystem.service.*;
import cn.caskm.souvenirshopsystem.utils.UserContext;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper, GoodsOrder> implements GoodsOrderService {

    private final ShoppingCartService shoppingCartService;

    private final GoodsService goodsService;

    private final GoodsCommentService commentService;

    private final UserCouponService userCouponService;

    private final CouponService couponService;

    @Override
    public Result<PageDTO<GoodsOrder>> page(PageQuery query) {
        // 获取参数
        Long pageNum = query.getPageNum();
        if (pageNum == null) {
            pageNum = BizConstants.DEFAULT_PAGE_NUM;
        }
        Long pageSize = query.getPageSize();
        if (pageSize == null) {
            pageSize = BizConstants.DEFAULT_PAGE_SIZE;
        }

        // 查询数据
        Page<GoodsOrder> page = lambdaQuery()
                .orderByDesc(GoodsOrder::getCreateTime)
                .page(new Page<>(pageNum, pageSize));

        List<GoodsOrder> records = page.getRecords();
        return Result.success(PageDTO.of(records, page.getPages(), page.getTotal()));
    }

    @Override
    public Result<List<GoodsOrder>> getAll() {
        List<GoodsOrder> list = lambdaQuery()
                .orderByDesc(GoodsOrder::getCreateTime)
                .list();
        return Result.success(list);
    }

    @Override
    public Result<GoodsOrder> detail(Integer id) {
        GoodsOrder goodsOrder = getById(id);
        if (goodsOrder == null) {
            throw new BizException("订单信息不存在");
        }
        return Result.success(goodsOrder);
    }

    @Override
    public void saveOrUpdateEntity(GoodsOrder goodsOrder) {
        if (goodsOrder.getOrderId() == null) {
            // 新增订单
            goodsOrder.setCreateTime(LocalDateTime.now());
            // 默认设置订单状态为下单
            if (goodsOrder.getOrderStatus() == null) {
                goodsOrder.setOrderStatus(0);
            }
            save(goodsOrder);
        } else {
            // 修改订单
            updateById(goodsOrder);
        }
    }

    @Override
    @Transactional
    public Integer submitOrder(Integer goodsId, Integer goodsNum, Long userCouponId) {
        // 获取登录信息
        Long userId = UserContext.getUser();

        // 存储各个商品提交的份数
        Map<Integer, Integer> numMap = new HashMap<>();

        // 获取订单的商品信息
        List<Goods> listGoods = new ArrayList<>();
        if (goodsId != null) {
            // 单个商品购买
            Goods goods = goodsService.getById(goodsId);
            if (goods == null) {
                throw new BizException("商品不存在");
            }
            listGoods.add(goods);
            numMap.put(goodsId, goodsNum);
        } else {
            // 购物车购买
            List<ShoppingCart> cartGoods = shoppingCartService.lambdaQuery()
                    .eq(ShoppingCart::getUserId, userId.intValue())
                    .eq(ShoppingCart::getFlag, 1)
                    .list();
            if (CollUtil.isEmpty(cartGoods)) {
                throw new BizException("购物车商品信息为空");
            }
            // 添加商品购买份数信息
            cartGoods.forEach(cart -> numMap.put(cart.getGoodsId(), cart.getGoodsNum()));
            // 获取商品信息
            Set<Integer> goodsIds = cartGoods.stream().map(ShoppingCart::getGoodsId).collect(Collectors.toSet());
            List<Goods> goodsList = goodsService.lambdaQuery()
                    .in(Goods::getGoodsId, goodsIds)
                    .eq(Goods::getStatus, "0")
                    .eq(Goods::getSetIndex, "1")
                    .eq(Goods::getDeleteStatus, "0")
                    .list();
            listGoods.addAll(goodsList);

            // 移除购物车信息
            List<Integer> cartIds = cartGoods.stream().map(ShoppingCart::getCartId).collect(Collectors.toList());
            shoppingCartService.removeBatchByIds(cartIds);
        }

        // 计算订单总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Goods goods : listGoods) {
            Integer currentGoodsPayNum = numMap.get(goods.getGoodsId());
            BigDecimal itemAmount = goods.getGoodsPrice().multiply(new BigDecimal(currentGoodsPayNum));
            totalAmount = totalAmount.add(itemAmount);
        }

        // 处理优惠券逻辑
        BigDecimal discountAmount = BigDecimal.ZERO;
        
        if (userCouponId != null) {
            // 查询用户优惠券
            UserCoupon userCoupon = userCouponService.getById(userCouponId);
            if (userCoupon == null) {
                throw new BizException("优惠券不存在");
            }
            
            // 验证优惠券归属
            if (!userCoupon.getUserId().equals(userId.intValue())) {
                throw new BizException("优惠券不属于当前用户");
            }
            
            // 验证优惠券状态
            if (!"0".equals(userCoupon.getStatus())) {
                throw new BizException("优惠券不可用");
            }
            
            // 验证优惠券是否过期
            if (LocalDateTime.now().isAfter(userCoupon.getExpireTime())) {
                throw new BizException("优惠券已过期");
            }
            
            // 查询优惠券详情
            Coupon coupon = couponService.getById(userCoupon.getCouponId());
            if (coupon == null) {
                throw new BizException("优惠券配置不存在");
            }
            
            // 验证订单金额是否满足优惠券使用条件
            if (coupon.getMinAmount() != null && totalAmount.compareTo(coupon.getMinAmount()) < 0) {
                throw new BizException("订单金额不满足优惠券使用条件，需满" + coupon.getMinAmount() + "元");
            }
            
            // 计算优惠金额
            discountAmount = calculateDiscount(totalAmount, coupon);
        }

        // 计算实际支付金额
        BigDecimal finalPrice = totalAmount.subtract(discountAmount);
        if (finalPrice.compareTo(BigDecimal.ZERO) < 0) {
            finalPrice = BigDecimal.ZERO;
        }

        // 构建商品ID和数量的字符串（用分号分隔）
        StringBuilder goodsIdsBuilder = new StringBuilder();
        StringBuilder goodsNumsBuilder = new StringBuilder();
        int totalGoodsNum = 0;
        
        for (Goods goods : listGoods) {
            Integer currentGoodsId = goods.getGoodsId();
            Integer currentGoodsNum = numMap.get(currentGoodsId);
            
            if (goodsIdsBuilder.length() > 0) {
                goodsIdsBuilder.append(";");
                goodsNumsBuilder.append(";");
            }
            goodsIdsBuilder.append(currentGoodsId);
            goodsNumsBuilder.append(currentGoodsNum);
            totalGoodsNum += currentGoodsNum;
        }

        // 创建一个订单（包含所有商品）
        GoodsOrder order = new GoodsOrder();
        order.setOrderUser(userId.intValue());
        order.setOriginalPrice(totalAmount);  // 订单原价
        order.setDiscountAmount(discountAmount);  // 优惠金额
        order.setPrice(finalPrice);  // 实际支付金额
        order.setUserCouponId(userCouponId);  // 优惠券ID
        order.setCreateTime(LocalDateTime.now());
        
        // 如果只有一个商品，使用goodsId字段
        if (listGoods.size() == 1) {
            order.setGoodsId(listGoods.get(0).getGoodsId());
            order.setOrderNum(numMap.get(listGoods.get(0).getGoodsId()));
        } else {
            // 多个商品，使用goodsIds和goodsNums字段
            order.setGoodsIds(goodsIdsBuilder.toString());
            order.setGoodsNums(goodsNumsBuilder.toString());
            order.setOrderNum(totalGoodsNum);  // 总数量
        }
        
        order.setOrderStatus(1); // 已付款
        
        // 保存订单
        save(order);

        // 使用优惠券（标记为已使用）
        if (userCouponId != null) {
            userCouponService.useCoupon(userCouponId, order.getOrderId());
        }
        
        // 返回订单ID
        return order.getOrderId();
    }

    /**
     * 计算优惠金额
     */
    private BigDecimal calculateDiscount(BigDecimal orderAmount, Coupon coupon) {
        BigDecimal discount = BigDecimal.ZERO;
        
        // 0:满减券 1:折扣券 2:免费券
        String couponType = coupon.getCouponType();
        
        if ("0".equals(couponType)) {
            // 满减券：直接减免固定金额
            discount = coupon.getDiscountAmount() != null ? coupon.getDiscountAmount() : BigDecimal.ZERO;
        } else if ("1".equals(couponType)) {
            // 折扣券：按折扣率计算，不超过最大优惠金额
            if (coupon.getDiscountRate() != null) {
                // 折扣金额 = 订单金额 * (1 - 折扣率)
                BigDecimal rate = BigDecimal.ONE.subtract(coupon.getDiscountRate());
                discount = orderAmount.multiply(rate).setScale(2, RoundingMode.HALF_UP);
                
                // 如果有最大优惠金额限制
                if (coupon.getMaxDiscountAmount() != null && discount.compareTo(coupon.getMaxDiscountAmount()) > 0) {
                    discount = coupon.getMaxDiscountAmount();
                }
            }
        } else if ("2".equals(couponType)) {
            // 免费券：全免
            discount = orderAmount;
        }
        
        return discount;
    }

    @Override
    public PageDTO<MyOrderVO> listMyOrder(MyOrderQuery query) {
        // 获取登录用户
        Long userId = UserContext.getUser();

        // 分页查询订单信息
        String status = query.getStatus();
        Long pageNum = query.getPageNum();
        Long pageSize = query.getPageSize();
        Page<GoodsOrder> page = lambdaQuery()
                .eq(GoodsOrder::getOrderUser, userId.intValue())
                .eq(status != null, GoodsOrder::getOrderStatus, status)
                .orderByDesc(GoodsOrder::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
        List<GoodsOrder> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            return PageDTO.empty();
        }

        // 收集所有需要查询的商品ID
        Set<Integer> allGoodsIds = new HashSet<>();
        for (GoodsOrder order : records) {
            if (order.getGoodsId() != null) {
                // 单个商品
                allGoodsIds.add(order.getGoodsId());
            } else if (StrUtil.isNotBlank(order.getGoodsIds())) {
                // 多个商品
                String[] ids = order.getGoodsIds().split(";");
                for (String id : ids) {
                    allGoodsIds.add(Integer.parseInt(id.trim()));
                }
            }
        }

        // 查询所有商品信息
        Map<Integer, Goods> goodsMap = Collections.emptyMap();
        if (CollUtil.isNotEmpty(allGoodsIds)) {
            List<Goods> goods = goodsService.listByIds(allGoodsIds);
            if (CollUtil.isNotEmpty(goods)) {
                goodsMap = goods.stream().collect(Collectors.toMap(Goods::getGoodsId, g -> g));
            }
        }

        // 查询评论信息
        Set<Integer> orderIds = records.stream().map(GoodsOrder::getOrderId).collect(Collectors.toSet());
        List<GoodsComment> comments = commentService.lambdaQuery()
                .in(CollUtil.isNotEmpty(orderIds), GoodsComment::getOrderId, orderIds)
                .eq(GoodsComment::getUserId, userId.intValue())
                .list();
        Map<Integer, Integer> orderCommentIdMap = comments.stream()
                .collect(Collectors.toMap(GoodsComment::getOrderId, GoodsComment::getCommentId));

        // 组装vo
        String searchGoodsName = query.getGoodsName();
        Map<Integer, Goods> finalGoodsMap = goodsMap;
        List<MyOrderVO> result = records.stream().map(item -> {
                    MyOrderVO vo = new MyOrderVO();
                    vo.setId(item.getOrderId());
                    vo.setPayNum(item.getOrderNum());
                    vo.setPrice(item.getPrice());  // 实际支付金额
                    vo.setOriginalPrice(item.getOriginalPrice());  // 商品原价
                    vo.setDiscountAmount(item.getDiscountAmount());  // 优惠金额
                    vo.setUserCouponId(item.getUserCouponId());  // 优惠券ID
                    vo.setStatus(item.getOrderStatus());
                    vo.setCommentId(orderCommentIdMap.get(item.getOrderId()));

                    // 判断是单个商品还是多个商品
                    if (item.getGoodsId() != null) {
                        // 单个商品
                        Integer goodsId = item.getGoodsId();
                        vo.setGoodsId(goodsId);
                        Goods currentGoods = finalGoodsMap.get(goodsId);
                        if (currentGoods != null) {
                            vo.setDesc(currentGoods.getGoodsDesc());
                            vo.setPicture(currentGoods.getImage());
                            vo.setGoodsName(currentGoods.getGoodsName());
                        }
                    } else if (StrUtil.isNotBlank(item.getGoodsIds())) {
                        // 多个商品
                        vo.setGoodsIds(item.getGoodsIds());
                        vo.setGoodsNums(item.getGoodsNums());
                        
                        String[] ids = item.getGoodsIds().split(";");
                        StringBuilder namesBuilder = new StringBuilder();
                        StringBuilder picturesBuilder = new StringBuilder();
                        
                        for (String id : ids) {
                            Integer goodsId = Integer.parseInt(id.trim());
                            Goods goods = finalGoodsMap.get(goodsId);
                            if (goods != null) {
                                if (namesBuilder.length() > 0) {
                                    namesBuilder.append(";");
                                    picturesBuilder.append(";");
                                }
                                namesBuilder.append(goods.getGoodsName());
                                picturesBuilder.append(goods.getImage());
                            }
                        }
                        
                        vo.setGoodsNames(namesBuilder.toString());
                        vo.setPictures(picturesBuilder.toString());
                        
                        // 设置第一个商品名称和图片（用于兼容）
                        if (ids.length > 0) {
                            Integer firstGoodsId = Integer.parseInt(ids[0].trim());
                            Goods firstGoods = finalGoodsMap.get(firstGoodsId);
                            if (firstGoods != null) {
                                vo.setGoodsName(firstGoods.getGoodsName());
                                vo.setPicture(firstGoods.getImage());
                                vo.setDesc(firstGoods.getGoodsDesc());
                            }
                        }
                    }
                    
                    return vo;
                })
                .filter(item -> StrUtil.isBlank(searchGoodsName) || 
                        (item.getGoodsName() != null && item.getGoodsName().contains(searchGoodsName)) ||
                        (item.getGoodsNames() != null && item.getGoodsNames().contains(searchGoodsName)))
                .collect(Collectors.toList());

        return PageDTO.of(result, page.getPages(), page.getTotal());
    }

}
